from django.shortcuts import render

# Create your views here.
from django.views import View
from .models import *
from rest_framework.views import APIView
from myapp import myserializers
from rest_framework.response import Response
from utils.captcha.captcha import captcha
from django.http import HttpResponse
import memcache
import requests
import json

server = memcache.Client(["39.106.229.25:11211"])


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get("username")
        imagecode = request.data.get("imagecode")

        code = server.get(username)

        print(code)

        if imagecode.lower() != code.lower():
            return Response({'code': 500, 'data': '验证码错误'})

        user_ser = myserializers.UserSerializer(data=request.data)
        if user_ser.is_valid():
            user_ser.save()
            return Response({'code': 200, 'data': '创建成功'})
        else:
            return Response({'code': 500, 'data': '创建失败'})


class LoginView(APIView):
    def post(self, request):
        data = request.data
        print(data)
        user_ser = User.objects.filter(username=data['username'], password=data['password']).first()
        if user_ser:
            return Response({'code': 200, 'data': '登陆成功'})
        else:
            return Response({'code': 500, 'data': '登陆失败,账号不存在'})


class Imges(APIView):  # 验证码
    def get(self, request):
        name, text, image = captcha.generate_captcha()
        response = HttpResponse(image)
        response["Content-Type"] = "image/jpg"
        username = request.GET.get('username')
        server.set(username, text, 60)
        return response


class WeiBoView(APIView):
    def post(self, request):
        token = request.data.get('token')
        params = {
            'client_id': '297351690',
            'client_secret': '8e24e86fd5dfa8d95675316bd969f9f1',
            'grant_type': 'authorization_code',
            'code': token,
            'redirect_uri': 'http://127.0.0.1:8080/weibo_callback'
        }
        url = 'https://api.weibo.com/oauth2/access_token'

        res = requests.post(url, data=params).text
        dict = json.loads(res)
        # print(dict['uid'])
        return Response({
            'code': 200,
            'uid': dict['uid']
        })


class WeiBoBindView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        uid = request.data.get('uid')
        # print(username, password, uid)

        user_yanzheng = User.objects.filter(username=username).first()
        if user_yanzheng:
            if user_yanzheng.password != password:
                return Response({
                    'code': 500,
                    'data': '用户或者密码错误'
                })
        else:
            user = User.objects.create(username=username, password=password)

        weibo = Weibo.objects.filter(uid=uid).first()
        if weibo:
            return Response({
                'code': 201,
                'data': '用户已绑定过，跳转登陆页面'
            })

        # 微博绑定表的添加
        user = User.objects.filter(username=username).first()
        Weibo.objects.create(uid=uid, user=user)

        return Response({
            'code': 200,
            'data': '绑定成功'
        })
